package jgl.vajra.driver.widget.base;

import android.content.Context;
import android.os.Handler;
import android.os.Process;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import jgl.vajra.driver.BuildConfig;
import jgl.vajra.driver.R;
import jgl.vajra.driver.bean.LoginInfoBean;
import jgl.vajra.driver.bean.UserInfo;
import jgl.vajra.driver.constant.AppConfig;
import jgl.vajra.driver.manager.DownloadTasksManager;
import jgl.vajra.driver.manager.IntentManager;
import jgl.vajra.driver.manager.SDKManager;
import jgl.vajra.driver.part.splash.SplashActivity;
import jgl.vajra.driver.widget.ActivityLifecycleHelper;
import jgl.vajra.driver.widget.ExceptionHandler;
import jgl.vajra.driver.widget.db.DaoMaster;
import jgl.vajra.driver.widget.db.DaoSession;
import jgl.vajra.driver.widget.manager.DBDaoManager;
import jgl.vajra.driver.widget.pagemanage.PageManager;
import jgl.vajra.driver.widget.push.PushManager;
import jgl.vajra.driver.widget.utils.CommonUtils;
import jgl.vajra.driver.widget.utils.UIUtils;

import com.baidu.mapapi.SDKInitializer;
import com.bumptech.glide.request.target.ViewTarget;
import com.facebook.stetho.Stetho;
import com.github.yuweiguocn.library.greendao.MigrationHelper;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;

import java.util.HashMap;
import java.util.UUID;

/**
 * @Author zhangshuqi
 * @CreateTime 2018/3/15
 * @Describe
 */

public class BaseApplication extends MultiDexApplication {
    private static Context mContext;
    private static DaoSession mDaoSession;
    private static DaoMaster daoMaster;
    public static int count;
    private static UserInfo userInfo;
    private ActivityLifecycleHelper mActivityLifecycleHelper;
    private static Handler mHandler;
    private static int mMainTreadId;
    private static int appStatusModel = BuildConfig.appStatusModel;
    private static LoginInfoBean loginInfoBean;
    private static String mUuid;


   /* public static PushAgent getPushAgent() {
        return mPushAgent;
    }

    private static PushAgent mPushAgent;*/

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();
        mMainTreadId = Process.myTid();
        mContext = getApplicationContext();
        initSQL();
        initLogger();
        initPageManager();
        initUMeng();
        initExceptionHandler();
        setDensity();
        registerActivityLifecycleCallbacks(mActivityLifecycleHelper = new ActivityLifecycleHelper());
//        initX5WebView();
        initUUid();
        Stetho.initializeWithDefaults(this);
        ViewTarget.setTagId(R.id.glide_tag);
        initFileDownload();
        initPushHandler();
        initScreencast();
        initRefreshLayout();
        SDKManager.getInstance().initSDK(getContext());

        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(this);
    }


    private void initRefreshLayout() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                ClassicsHeader classicsHeader = new ClassicsHeader(context);
                classicsHeader.setEnableLastTime(false);
                           /* <com.scwang.smartrefresh.layout.header.ClassicsHeader
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:srlFinishDuration="500"
                app:srlEnableLastTime="true"
                app:srlClassicsSpinnerStyle="FixedBehind"
                app:srlTextSizeTitle="16sp"
                app:srlTextSizeTime="10dp"
                app:srlTextTimeMarginTop="2dp"
                app:srlDrawableArrowSize="20dp"
                app:srlDrawableProgressSize="20dp"
                app:srlDrawableMarginRight="20dp"
                app:srlDrawableProgress="@drawable/ic_progress_puzzle"/>*/
                classicsHeader.setTextSizeTitle(14);
                classicsHeader.setDrawableArrowSize(16);
                classicsHeader.setDrawableProgressSize(16);
                classicsHeader.setDrawableMarginRight(16);
                classicsHeader.setAccentColor(UIUtils.getColor(R.color.gray_66));
                classicsHeader.setProgressDrawable(UIUtils.getContext().getResources().getDrawable(R.drawable.ic_progress_puzzle));
                classicsHeader.setSpinnerStyle(SpinnerStyle.FixedBehind);
                // layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return classicsHeader;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                ClassicsFooter classicsFooter = new ClassicsFooter(context);
                classicsFooter.setAccentColor(UIUtils.getColor(R.color.gray_66));
                classicsFooter.setTextSizeTitle(14);
                classicsFooter.setDrawableArrowSize(16);
                classicsFooter.setDrawableProgressSize(16);
                classicsFooter.setDrawableMarginRight(16);
                classicsFooter.setDrawableSize(16);
                return classicsFooter;
            }
        });
    }

    private void initPushHandler() {
        // 设置打开应用首个Activity
        PushManager.getInstance().setLauncherClass(SplashActivity.class);
        // 设置推送处理接口
        PushManager.getInstance().setPushHandlerListener(new PushManager.PushHandlerListener() {
            @Override
            public boolean isHandlerPush(String value) {
                // 防止为null
                if (TextUtils.isEmpty(value)) {
                    return false;
                }
                // ---
                if (value.equals(SplashActivity.class.getSimpleName())) {
                    return false; // 属于欢迎页面则不进行处理
                }
                Logger.d("isHandlerPush-----" + value);
                // 默认进行处理
                return true;
            }

            @Override
            public void onPushHandler(FragmentActivity activity, String pushData, String pushType) {
                StringBuffer buffer = new StringBuffer();
                buffer.append("\npushType: " + pushType);
                buffer.append("\npushData: " + pushData);
                Logger.e("pushManager" + buffer);
                IntentManager.toMessageCenterActivity(activity);

            }
        });
    }


    private void initFileDownload() {
        // just for open the log in this demo project.
        FileDownloadLog.NEED_LOG = true;

        /**
         * just for cache Application's Context, and ':filedownloader' progress will NOT be launched
         * by below status, so please do not worry about performance.
         * @see FileDownloader#init(Context)
         */
        FileDownloader.setupOnApplicationOnCreate(this)
                .connectionCreator(new FileDownloadUrlConnection
                        .Creator(new FileDownloadUrlConnection.Configuration()
                        .connectTimeout(15_000) // set connection timeout.
                        .readTimeout(15_000) // set read timeout.
                ))
                .idGenerator(new DownloadTasksManager.VideoDownloadIdGenerator())
                .commit();

    }


    private void initUMeng() {//d7d7c4da3a8b6a2c4b870ad29741e148
        UMConfigure.preInit(this, "5f048f6a0cafb24a8e000016"
                , "umeng");


    }


    private static void initUUid() {
        //if (TextUtils.isEmpty(mUuid))
        mUuid = UUID.randomUUID().toString();
    }


    public static String getAppTagByUUID() {

        Logger.d("uuid====" + mUuid);
        return mUuid;
    }

    private void initX5WebView() {
        // 在调用TBS初始化、创建WebView之前进行如下配置
        HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        //如果没有这个内核，允许在WIFI情况下去下载内核
        QbSdk.setDownloadWithoutWifi(true);
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Logger.d("----------onViewInitFinished" + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                Logger.d("----------onCoreInitFinished");
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    public void initScreencast() {
      /*  //TODO appId和appSecret需与包名绑定，获取方式请咨询Polyv技术支持
        PolyvScreencastHelper.init("10747", "34fa2201e4e7441635ca4fa97fd4b21e");//该appId，appSecret仅能在demo中使用
        //初始化单例
        PolyvScreencastHelper.getInstance(this);*/
    }

    //加密秘钥和加密向量，在后台->设置->API接口中获取，用于解密SDK加密串
    //值修改请参考https://github.com/easefun/polyv-android-sdk-demo/wiki/10.%E5%85%B3%E4%BA%8E-SDK%E5%8A%A0%E5%AF%86%E4%B8%B2-%E4%B8%8E-%E7%94%A8%E6%88%B7%E9%85%8D%E7%BD%AE%E4%BF%A1%E6%81%AF%E5%8A%A0%E5%AF%86%E4%BC%A0%E8%BE%93
    /**
     * 加密秘钥
     */
    // private String aeskey = "Zx6uAK9Hy75iMIq1";
    private String aeskey = "VXtlHmwfS2oYm0CZ";
    // private String aeskey = "VXtlHmwfS2oYm0CZ";
    private String iv = "2u9gDPKdX6GyQJKU";
    //private String iv = "XGxnuUGofPXzKb8s";
    // private String config = "HNxFViQZol0ywAU48FHqghL36wimEGsGA3VJSeslCHElW2tgWfe4GLn1D0ZOtM/xacCPGgbVLUUi35CFPoTtnZxaLymfnVbvq7lDN4qRDKDPkRxgL0Ouh9VtZr2oz8ZdocwjERtMy0lalhmbsOO2Lw==";
    private String config = "NWL8GFttqtxXpfJhEotV5di+yjOMtoMAYMzQb1cZV04CtgbHZDkR8opTNKk2Spgx9utHEstnnuGqRHMx4J10Lake9NhIwnCMBJyV6uAdJEJ5iyMac4cw0+oDUrbKzL3BKmRVGmkVgVyhdRRK6gudHA==";


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    private void initExceptionHandler() {
        if (!CommonUtils.isAppRelease()) {

            ExceptionHandler catchHandler = ExceptionHandler.getInstance();
            catchHandler.init(getApplicationContext());
            catchHandler.collectDeviceInfo(getApplicationContext());
        }

    }

    private void setDensity() {
        //   DensityManager.setDensity(this);
    }


    private void initPageManager() {
        PageManager.initInApp(mContext);
    }

    private void initSQL() {
        getDaoSession();
    }

    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)      //（可选）是否显示线程信息。 默认值为true
                .methodCount(5)               // （可选）要显示的方法行数。 默认2
                .tag("xxBookRead")                  //（可选）每个日志的全局标记。 默认PRETTY_LOGGER（如上图）
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return getAppStatusModel() != AppConfig.TYPE_RELEASE;
                //    return true;
            }
        });
    }


    /**
     * 取得DaoMaster
     *
     * @return daoMaster
     */
    private static DaoMaster getDaoMaster() {
        MigrationHelper.DEBUG = true;
        DBDaoManager helper = new DBDaoManager(mContext, "android.vajra.db");
        daoMaster = new DaoMaster(helper.getWritableDatabase());

        return daoMaster;
    }

    /**
     * 取得DaoSession
     *
     * @return daoSession
     */
    public static DaoSession getDaoSession() {
        if (mDaoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster();
            }
            mDaoSession = daoMaster.newSession();

        }
        return mDaoSession;
    }


    public static Context getContext() {
        return mContext;
    }

    public ActivityLifecycleHelper getActivityLifecycleHelper() {
        return mActivityLifecycleHelper;
    }

    public static Handler getMainHandler() {
        return mHandler;
    }

    public static long getMainTreadId() {
        return mMainTreadId;
    }

    public static int getAppStatusModel() {
        return appStatusModel;
    }

    public static void setUserInfo(UserInfo userInfo) {
        BaseApplication.userInfo = userInfo;
    }

    public static UserInfo getUserInfo() {
        return userInfo;
    }


    public static void setUuid(String mUuid) {
        BaseApplication.mUuid = mUuid;
    }

    public static String getUuid() {
        return mUuid;
    }

    public static LoginInfoBean getLoginData() {
        return loginInfoBean;
    }

    public static void setLoginData(LoginInfoBean loginInfo) {
        loginInfoBean = loginInfo;
    }

}
